package org.firecloud.h5fun.controller.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.ColumnBean;
import org.firecloud.h5fun.model.javabean.ProjectBean;
import org.firecloud.h5fun.model.javabean.SearchQueryBean;

public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Connection connection = null;
		List<ProjectBean> projects = null;
		try {
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			SearchQueryBean query = new SearchQueryBean();
			connection = config.getConn();
			
			query.setColumnId((byte) 0);
			query.setOrderBy(SearchQueryBean.OrderByType_ID);
			projects = new ArrayList<ProjectBean>();
			CommonQuery.select_projects(connection, projects, query, config.getMainPageSize(), 0);
			req.setAttribute("new0", projects);
			
			query.setColumnId((byte) 0);
			query.setOrderBy(SearchQueryBean.OrderByType_COMMENTARY);
			projects = new ArrayList<ProjectBean>();
			CommonQuery.select_projects(connection, projects, query, config.getMainPageSize(), 0);
			req.setAttribute("top0", projects);
			
			List<ColumnBean> columns = (List<ColumnBean>) req.getServletContext().getAttribute("columns");
			for (ColumnBean column : columns) {
				query.setColumnId(column.getId());
				query.setOrderBy(SearchQueryBean.OrderByType_ID);
				projects = new ArrayList<ProjectBean>();
				CommonQuery.select_projects(connection, projects, query, config.getMainPageSize(), 0);
				req.setAttribute("new" + column.getId(), projects);
				
				query.setColumnId(column.getId());
				query.setOrderBy(SearchQueryBean.OrderByType_COMMENTARY);
				projects = new ArrayList<ProjectBean>();
				CommonQuery.select_projects(connection, projects, query, config.getMainPageSize(), 0);
				req.setAttribute("top" + column.getId(), projects);
			}
			req.getRequestDispatcher("jsp/page-index.jsp").forward(req, resp);
		} catch (Exception e) {
			Logger.getRootLogger().error(e.toString());
			req.getRequestDispatcher("jsp/page-error.jsp").forward(req, resp);
			e.printStackTrace();
		} finally {
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().equals(e);
				}
			}
		}
	}
}